import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store"

Vue.use(VueRouter)

const routes = [
    {
        path: '/login',
        name: "登录",
        component: () => import('../views/Login.vue'),
        meta: {noLogin: true}
    },
    {
        path: '/',
        name: 'Manage',
        component: () => import('../views/Manage.vue'),

        redirect: "/home",
        children: [
            {path: 'home', name: "首页", component: () => import('../views/Home.vue')},
            {path: 'user', name: "用户管理", component: () => import('../views/User.vue')},
            {path: 'asset', name: "资产详情", component: () => import('../views/Asset.vue')},
            {path: 'lendin', name: "资产借出", component: () => import('../views/Lendin.vue')},
            {path: 'lendout', name: "资产还入", component: () => import('../views/Lendout.vue')},
            {path: 'lendaduit', name: "借出审核", component: () => import('../views/Lendaduit.vue')},
            {path: 'check', name: "购入审核", component: () => import('../views/Check.vue')},
            {path: 'submitAppliance', name: "购入申请", component: () => import('../views/SubmitAppliance.vue')},
            {path: 'maintainsubmit', name: "维修申报", component: () => import('../views/Maintainsubmit.vue')},
            {path: 'maintain', name: "维修情况", component: () => import('../views/Maintain.vue')},
            {path: 'person', name: "个人信息", component: () => import('../views/Person.vue')},
            // {path: 'swagger', name: "swagger文档", component: () => import('../views/Swagger.vue')},
        ]
    },
    {
        path: '/404',
        name: '404',
        component: () => import('../views/404.vue')
    },
    {
        path: "*", redirect: '/404' //未定义路由都到404
    }
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})
router['_path'] = routes[1].children;

// 路由守卫
router.beforeEach(({path, meta, name}, from, next) => {
    console.log(path, meta, name)
    if (!meta.noLogin && !isAuthenticated()) {
        // 此路由需要授权，请检查是否已登录
        // 如果未登录，重定向到登录页
        next({
            path: '/login'
        });
    } else if (isAuthenticated() && path == '/login') {
        next({path: '/'})//登陆了不用重新登录
    } else {
        localStorage.setItem("currentPathName", name)  // 设置当前的路由名称，为了在Header组件中去使用
        store.commit("setPath")  // 触发store的数据更新
        next()  // 放行路由
    }
})

function isAuthenticated() {
    return Boolean(localStorage.getItem("user"));
}

export default router